<template>
  <Modal v-model="isShow"
         footer-hide
         width="700"
         @on-cancel="closeEvent"
         :mask-closable="false"
         title="用户授权">
    <Form ref="form" class="form" :label-width="80" :model="formData" :rules="rules">
      <Transfer
          class="permission"
          :data="allRoleList"
          :list-style="listStyle"
          :titles="['用户未拥有的角色','用户拥有的角色']"
          :target-keys="formData.roleCodes"
          filterable
          @on-change="handleChange"/>
      <FormItem class="form-bottom-btn">
        <Button @click="submitBtnClick" type="primary">保存</Button>
      </FormItem>
    </Form>
  </Modal>
</template>
<script>

import {getAllRole} from "@/api/sys/role";
import {getDictDataName} from "@/util";
import {getAllUserRole, saveOrUpdateUserRole} from "@/api/sys/user";
import {RESPONSE_CODE_SUCCESS} from "@/constant/response";
import {Message} from "view-ui-plus";

const formData = {
  userName: '',
  roleCode: [],
}
export default {
  data() {
    return {
      isShow: false,
      user: undefined,
      listStyle: {
        width: '300px',
        height: '300px'
      },
      allRoleList: [],
      rules: {},
      formData: {
        userName: '',
        roleCodes: [],
      }
    }
  },
  methods: {
    submitBtnClick() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        let saveData = this.$utils.clone(this.formData)
        saveOrUpdateUserRole(saveData).then(res => {
          if (res.code == RESPONSE_CODE_SUCCESS) {
            this.$emit("ok")
            Message.success("保存成功")
            this.isShow = false
          }
        })
      })
    },
    show({user}) {
      this.user = user
      this.formData = this.$utils.clone(formData)
      this.formData.userName = user.userName
      Promise.all([getAllRole({}), getAllUserRole({
        userName: this.user.userName
      })]).then(async res => {
        let newAllRoleList = [];
        let allRoleList = res[0].data
        for (let item of allRoleList) {
          newAllRoleList.push({
            key: item.code,
            label: item.name + "-" + item.code + "-" + (await getDictDataName('YesNo:EnableDisable', item.roleStatus))
          })
        }
        this.allRoleList = newAllRoleList;

        let userRole = res[1].data
        let newUserRoleCodes = [];
        for (let item of userRole) {
          newUserRoleCodes.push(item.roleCode)
        }
        this.formData.roleCodes = newUserRoleCodes;

        this.isShow = true
      })
    },
    handleChange(newTargetKeys) {
      this.formData.roleCodes = newTargetKeys;
    },
    closeEvent() {
      this.formData = this.$utils.clone(formData)
    },
  }
}
</script>
